package com.soushin.mvpdemo.network;

import com.blankj.ALog;
import com.zhouyou.http.interceptor.BaseExpiredInterceptor;

import java.io.IOException;

import okhttp3.Response;
import com.soushin.mvpdemo.Utils.GsonUtil;
import com.soushin.mvpdemo.model.ResultModel;

/**
 * 处理token过期等问题
 *
 * @author SouShin
 * @time 2018/12/10 13:32
 */
public class TokenInterceptor extends BaseExpiredInterceptor {
    private ResultModel resultModel;

    @Override
    public boolean isResponseExpired(Response response, String bodyString) {
        resultModel = GsonUtil.toBean(bodyString, ResultModel.class);
        /*if (resultModel != null) {
            ALog.e("token拦截isResponseExpired", bodyString);
            return resultModel.getData() != null;
        }*/
        return false;
    }

    /**
     * 只有上面配置的过期情况才会执行这里
     * token 过期处理方案
     * 1 跳转登录页
     * 2 自动请求登录接口刷新token 并继续该接口的业务
     * @param chain
     * @param bodyString
     * @return
     */
    @Override
    public Response responseExpired(Chain chain, String bodyString) {
        ALog.e("token拦截responseExpired", bodyString);
        HttpClient.disposeRequest();
//        App.goLogin();
        if (resultModel != null) {
            try {
                //业务出错,可以把所有HTTP请求干掉.
                return chain.proceed(chain.request());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
